<?
// Get username and password details of viewer
$un = stripslashes($_COOKIE['un']);
$pwd = stripslashes($_COOKIE['pwd']);
if(!file_exists(SRV_ROOT . '/users/' . $un)) {
	$un = '';
	$pwd = '';
}

$pid = $_SERVER['PATH_INFO']; // Project ID
$pid = substr($pid, 1, strlen($pid));
if(!file_exists(SRV_ROOT . '/projects/' . $pid) || ($pid == '')) { // Not a valid ID? Give a 404.
	httperror(404);
}

// Check for actions
if($_GET['action'] != '') {
	if($_GET['action'] == 'love') {
		// Love it
		if($un != '') {
			$lvs = explode(chr(13), file_get_contents(SRV_ROOT . '/projects/' . $pid . '/loves'));
			if(in_array($un, $lvs)) {
				// Unlove
				foreach($lvs as $key => $value) {
					if($key == $un || $key == '') {
						unset($lvs[$key]);
					}
				}
			} else {
				// Love
				$lvs[] = $un;
			}
			file_put_contents(SRV_ROOT . '/projects/' . $pid . '/loves', implode(chr(13), $lvs));
			echo sizeof($lvs);
			die;
		}
	}
}

// Get all info beforehand and store in it variables
$ptitle = clearHTML(file_get_contents(SRV_ROOT . '/projects/' . $pid . '/title')); // Project title
$pdescription = stripslashes(file_get_contents(SRV_ROOT . '/projects/' . $pid . '/description')); // Project description
$plicense = file_get_contents(SRV_ROOT . '/projects/' . $pid . '/license'); // Project license
$pcreator = file_get_contents(SRV_ROOT . '/projects/' . $pid . '/creator'); // Project creator
$pdate = file_get_contents(SRV_ROOT . '/projects/' . $pid . '/uploadtime') + $tzone; // Project upload time in unix timestamp
$pmod = file_get_contents(SRV_ROOT . '/projects/' . $pid . '/mod'); // Mod used for project
$pviews = file_get_contents(SRV_ROOT . '/projects/' . $pid . '/views'); // Project views
$ploves = explode(chr(13), file_get_contents(SRV_ROOT . '/projects/' . $pid . '/loves')); // Project love-its
$pblocked = file_exists(SRV_ROOT . '/projects/' . $pid . '/blocked'); // Is the project blocked?
$canedit = $un == $pcreator || $is_admin;

if ($pblocked) {
	header('HTTP/1.1 410 Gone');
}

// Add a view to the project
$pviews += 1;
file_put_contents(SRV_ROOT . '/projects/' . $pid . '/views', $pviews);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php $_GET["title"] = $ptitle . " - Mod Share"; ?>
<? include SRV_ROOT . "/includes/head.php" ?>
</head>

<body>

<div id="container">
<? include SRV_ROOT . '/includes/header.php' ?>
<? include SRV_ROOT . '/includes/sidebar.php' ?>

  <div id="mainContent">
	<?php if (file_exists(SRV_ROOT . '/users/' . $pcreator . '/blocked')) {
		echo '<h3 style="color:#F00">The account that uploaded this project has been suspended, so you may not access this project.</h3>';
	} else {?>
    <h1><? echo '<span id="titletext"';
	if ($canedit) echo ' ondblclick="editTitle()"';
	echo '>' . $ptitle . '</span>'; if($canedit) {echo ' <a onclick="editTitle();" style="cursor: pointer;" id="titlebutton">(Edit)</a>';}?></h1>
    <table border="0" width="100%">
    <tr><th>By <? echo '<a href="/user/' . $pcreator . '">' . $pcreator . '</a>'; ?></th>
	<th width="160"><? if ($pblocked) echo '***'; else echo $pviews; ?> Views</th><?php /* if (!$pblocked) { ?><th width="160" id="loveit"><? echo sizeof($ploves); ?> Loves</th><?php }  */?></tr>
    <tr>
	<td><? echo gmdate('d M y, ', $pdate) . 'at ' . gmdate('H:i', $pdate); ?></td><? if($un != '') { ?>
	<?php if ($uvalid && file_exists(SRV_ROOT . "/users/$un/bookmarks") && strstr(file_get_contents(SRV_ROOT . "/users/$un/bookmarks"), $pid)) { ?>
		<td width="180">You bookmarked this project!</td>
	<?php } else { ?>
	<td width="180"><a onclick="bookmarkProject();" id="bmarkBtn" style="vertical-align: middle; cursor: pointer;"><img src="/misc/img/favi.png" width="18" height="18" />Bookmark this project</a></td><?php } ?>
	<?php /*<td width="180"><a href="javascript:loveit(this)" id="lovebutton"><?php if (!$pblocked) { ?><img src="/misc/img/lovei.png" width="18" height="18" />
		<? if(in_array($un, $ploves)) {echo 'Unlove';} else {echo 'Love';} ?> this project</a></td><? } */} ?></tr>
    </table>
    
    <div id="description" style="margin-bottom: 8px;">
    <h3 style="padding-top: 0px; padding-bottom: 0px; margin-top: 2px;">Description<? if($canedit) {echo ' <a onclick="editDescription();" style="cursor: pointer;" id="descriptionbutton">(Edit)</a>';} ?></h3>
    <p id="descriptiontext"><? // Description
    if(trim($pdescription) != '') {
		echo clearHTML($pdescription);
		if ($pblocked) {
			echo '<h3 style="color:#F00">This project is blocked - all copies on your computer should be deleted for safety.</h3>';
		}
	} else {
		echo '<span style="font-style: italic;">The creator did not put any description for this project.</span>';
	}
	?></p>
    </div>

    <div id="project">
	<p><i>Most added blocks do not work in this player. Download for the full experience!</i></p>
	<?php
	if ($pblocked) {
		echo '<p>This project is blocked, so the mod is irrelevant.</p>';
	} else {
		echo '<p>This project was made in <b>' . getMod($pmod) . '</b></p>';
	}
	?>
	 <div id="player">
		<?php if (!strstr(getMod($pmod), 'byob')) { ?>
		<object id="flashplayer" width="482" height="387" style="display: inline; visibility: visible; position: relative; z-index: 1000; " type="application/x-shockwave-flash" data="/includes/PlayerOnly.swf">
            <param name="allowScriptAccess" value="sameDomain" />
            <param name="allowFullScreen" value="true" />
			<param name="flashvars" value="project=/projects/<?php echo $pid . "/" . file_get_contents(SRV_ROOT . "/projects/$pid/filename"); ?>" />
		</object> 
		<?php } else { ?>
			<h3>This project was made in BYOB, which does not work at all in the online player. Please download it.</h3>
		<?php } ?>
	 </div>
	</div>

    <p>This project is <? // License
	if($pblocked == true) {
		echo 'blocked. All existing copies on your computer should be deleted for your safety.';
	} elseif($plicense == 'pd') {
		echo 'in the public domain.';
	} elseif($plicense == 'ms') {
		echo 'protected under the <a href="/projlicense.php">Mod Share Project License</a>.';
	} elseif($plicense == 'cc') {
		echo 'protected under the Creative Commons Attribution Share-Alike License.';
	} elseif($plicense == 'arr') {
		echo 'copyrighted &copy; in ' . date('Y',$pdate) . ' to ' . $pcreator . ' - All Rights Reserved.';
	} else {
		echo 'copyrighted in' . date('Y',$pdate) . ' to its creator.';
	}
    ?></p>
	<table border="0" width="500" style="text-align:center">
	<tr><td width="50%" style="vertical-align: middle;"><? if($pblocked == false) { ?><a href="/projects/<?php echo $pid; echo "/"; echo file_get_contents(SRV_ROOT . "/projects/$pid/filename"); ?>"><img src="/misc/img/downloadi.png" alt="Download" /> Download this project</a> <? } else {echo '<span style="text-decoration: line-through;">Download disabled</span>';} ?></td>
	<td width="50%" style="vertical-align: middle;"><? if($pblocked == false) { ?><a href="/scripts/report.php?proj=<?php echo $pid; ?>"><img src="/misc/img/reporti.png" width="24" height="24" alt="Report" /> Report inappropriate project</a><? } else { echo 'Project already blocked';}?></td></tr>
	<?php if ($is_admin) { ?>
	<tr style="margin-top: 20px;"><td><?php if ($pblocked) { ?><a href="/admin/blockproj.php?un=block&proj=<?php echo $pid; ?>">Unblock this project</a><?php } else { ?><a href="/admin/blockproj.php?proj=<?php echo $pid; ?>">Block this project</a><?php } ?></td>
	<td><a href="/admin/feature.php?proj=<?php echo $pid; ?>">Feature this project</a></td></tr>
	<?php
	} ?>
	</table>
	<?php if (!$pblocked) { ?>
	<h3 style="margin-bottom: 0px;">Embed this project</h3>
	<table border="0">
	<tr><td>Embed into the forums:</td><td><input type="text" readonly="readonly" size="50" value="[embed]<?php echo $pid; ?>[/embed]" onclick="this.focus(); this.select();" /></td></tr>
	<tr><td>Link in the forums:</td><td><input type="text" readonly="readonly" size="50" value="[link]<?php echo $pid; ?>[/link]" onclick="this.focus(); this.select();" /></td></tr>
	</table>
	<h3 style="margin-bottom: 0px;">Recommend this project</h3>
	<table border="0">
	<?php //Google +1 and Facebook like buttons ?>
	<tr><td><!-- Place this tag where you want the +1 button to render -->
<?php if (!strstr($_SERVER['REMOTE_HOST'], 'w3.org')) { ?><g:plusone></g:plusone> <?php } ?>

<!-- Place this render call where appropriate -->
<script type="text/javascript">
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script></td><td><div id="fb-root"></div>
<script type="text/javascript">(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<?php if (!strstr($_SERVER['REMOTE_HOST'], 'w3.org')) { ?><div class="fb-like" data-href="http://modshare.tk/view/<?php echo $pid; ?>' data-send="false" data-width="400" data-show-faces="true"></div><?php } ?></td><td><!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style ">
<a class="addthis_button_preferred_1"></a>
<a class="addthis_button_preferred_2"></a>
<a class="addthis_button_preferred_3"></a>
<a class="addthis_button_preferred_4"></a>
<a class="addthis_button_compact"></a>
<a class="addthis_counter addthis_bubble_style"></a>
</div>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-4f56c01d49fcab49"></script>
<!-- AddThis Button END --></td></tr>
	</table>
	<?php } ?>
	<?php if (file_get_contents(SRV_ROOT . "/projects/$pid/editpwd") != "" && $pcreator != $un) { ?>
	<form action="/scripts/editproject.php?p=<?php echo $pid; ?>" method="post" enctype="multipart/form-data">
	<h3 style="margin-bottom: 0px;">Edit project</h3>
	<p>Password: <input type="password" name="pwd" /></p>
	</form>
	<?php } if ($pcreator == $un) { ?>
	<h3 style="margin-bottom: 0px;"><a href="/scripts/editproject.php?p=<?php echo $pid; ?>">Edit project</a></h3>
	<?php } if ($uvalid) { ?>
	<h3>Add a comment</h3>
	<textarea name="comment" id="comment" rows="4" style="width: 360px; font-family: Tahoma, Geneva, sans-serif; font-size: 12px;"></textarea>
	<br>
	<input type=submit value="Leave comment" style="width: 366px; min-height: 20px; margin-bottom: 4px;" onclick="addComment()">
	<?php }
	//if (file_exists(SRV_ROOT . "/projects/$pid/comments")) { ?>
	<a name="comments"></a>
	<h2>Comments</h2>
	<div id="commentDiv">
    <?php
	$_GET['p'] = $pid;
	$_GET['retr'] = true;
	include SRV_ROOT . '/scripts/comment.php';
	?>
	</div>
	<?php
	}
	?>
  </div>

  <?php if (!strstr($_SERVER['REMOTE_HOST'], 'w3.org')) { ?>
<script language="javascript" type="text/javascript">
	//retrComs();
	function addComment() {
		// Send comments
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
		} else {
			 req = new ActiveXObject("Microsoft.XMLHTTP");
		}
		req.open("POST", '/scripts/comment.php?p=<? echo $pid; ?>', true);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		v = document.getElementById("comment").value;
		document.getElementById("comment").value = 'Working...';
		while (v.indexOf("&") != -1) {
			v = v.replace("&", "!amp!");
		}
		req.send('comment=' + v);
		
		req.onreadystatechange = function() {
			if (req.readyState==4 && (req.status==200 || req.status == 410)) {
				retrComs();
				document.getElementById('comment').value = '';
			} else {
				document.getElementById('comment').value = 'Error: ' + req.status + '.';
			}
		}
	}
	
	function submitReply(cid) {
		// Send comments
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
		} else {
			 req = new ActiveXObject("Microsoft.XMLHTTP");
		}
		req.open("POST", '/scripts/comment.php?rep=2&p=<? echo $pid; ?>&c=' + cid, true);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		v = document.getElementById(cid).value;
		while (v.indexOf("&") != -1) {
			v = v.replace("&", "!amp!");
		}
		document.getElementById('comment').value = 'Working...';
		req.send('comment=' + v);
		
		req.onreadystatechange = function() {
			if (req.readyState==4 && (req.status==200 || req.status == 410)) {
				retrComs();
				document.getElementById('comment').value = '';
			} else {
				document.getElementById('comment').value = 'Error: ' + req.status + '.';
			}
		}
	}
	
	function deleteComment(cid) {
		// Delete comments
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
		} else {
			 req = new ActiveXObject("Microsoft.XMLHTTP");
		}
		req.open("GET", '/scripts/deletecomment.php?rep=1&p=<? echo $pid; ?>&c=' + cid, true);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.send();
		
		req.onreadystatechange = function() {
			if (req.readyState==4 && (req.status==200 || req.status == 410)) {
				retrComs();
			} else {
				if (req.status != 200) alert('Error: ' + req.status + ' - comment not deleted');
			}
		}
	}
	
	function retrComs() {
		// Get comments
		document.getElementById("commentDiv").innerHTML = 'Working...';
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
		} else {
			 req = new ActiveXObject("Microsoft.XMLHTTP");
		}
		req.open("POST", '/scripts/comment.php?p=<? echo $pid; ?>&retr=true', true);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.send('foo=bar');
		
		req.onreadystatechange = function() {
			if (req.readyState==4 && req.status==200) {
				var resp = req.responseText;
				document.getElementById('commentDiv').innerHTML = resp;
			} else {
				document.getElementById('commentDiv').innerHTML = 'Error: ' + req.status + '.';
			}
		}
	}
	
	function loveit(obj) {
		// Love this project
		document.getElementById("loveit").innerHTML = 'Working...';
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
		} else {
			 req = new ActiveXObject("Microsoft.XMLHTTP");
		}
		req.open("POST", '/pages/view.php?id=<? echo $pid; ?>&action=love', true);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
		req.send();
		
		req.onreadystatechange = function() {
			if (req.readyState==4 && req.status==200) {
				var resp = req.responseText;
				document.getElementById("loveit").innerHTML = resp + ' Loves';
				if(document.getElementById("lovebutton").innerHTML == 'Love this project') {
					document.getElementById("lovebutton").innerHTML = 'Unlove this project';
				} else {
					document.getElementById("lovebutton").innerHTML = 'Love this project';
				}
			}
		 }
	}
	function addReply(btton, cid) {
		//res = '<form action="/scripts/comment.php?rep=2&p=<?php echo $pid; ?>&c=' + cid + '" method="post" enctype="multipart/form-data">		<textarea name="comment" rows="4" style="width: 360px; font-family:Arial"></textarea><br><input type="submit" value="Post reply"></form>';
		res = '<textarea name="comment" rows="4" style="width: 360px; font-family:Arial" id="' + cid + '"></textarea><input type="submit" value="Post reply" onclick="submitReply(' + cid + ')"></form>';
		document.getElementById('p' + cid).innerHTML = res;
	}
	
    var flashapp = document.getElementById('flashplayer');

    function JSFillScreen(fillScreen) {
        if (fillScreen) {
            var r = flashapp.getBoundingClientRect();
            flashapp.style.left = -r.left + 'px';
            flashapp.style.top = -r.top + 'px';
			flashapp.style.position = 'relative';
            var h = window.innerHeight;
            if (typeof(w) != 'number') { // If IE:
                w = document.documentElement.clientWidth;
                h = document.documentElement.clientHeight;
            }
            setPlayerSize(w, h - 10);
        } else {
			flashapp.style.position = "inherit";
            setPlayerSize(482, 387);
            flashapp.style.left = flashapp.style.top = '0px';
        }
    }

    function setPlayerSize(w, h) {
        var isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") > 0;
        if (isFirefox) w += 1;
        if (navigator.appName == 'Microsoft Internet Explorer') {
            flashapp.style.width = w;
            flashapp.style.height = h;
        } else {
            flashapp.width = w;
            flashapp.height = h;
        }
    }
	
	<?php if ($uvalid) { ?>
	function bookmarkProject() {
		var pid = "<?php echo $pid; ?>";
		
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
		} else {
			 req = new ActiveXObject("Microsoft.XMLHTTP");
		}
		req.open("POST", '/scripts/bookmark.php', true);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
		req.send('pid=' + pid);
		
		req.onreadystatechange = function() {
			if (req.readyState==4 && req.status==200) {
				document.getElementById("bmarkBtn").innerHTML = "Project bookmarked!";
				reloadSidebar();
			} else {
				document.getElementById("bmarkBtn").innerHTML = "Failed: " + req.status + " error code. Please refresh the page and try again.";
			}
		}
	}
	<?php } if($canedit) { // Edit description/title ?>
var xxtxtxx = '<? echo str_replace("\r", '', str_replace("\n", '', str_replace("
", "' + String.fromCharCode(13) + '", str_replace("'", "' + String.fromCharCode(39) + '", stripslashes(clearSymbols($pdescription)))))); ?>';
	function editDescription() {
		var txt = xxtxtxx; //document.getElementById('descriptiontext').innerHTML;
		while (txt.indexOf("<br") != -1) {
			txt = txt.replace("<br>", "\n");
		}
		document.getElementById('descriptiontext').innerHTML = '<textarea rows="8" style="width: 98%; font-family:Arial">' + txt + '</textarea><br /><input type="button" onclick="submitDescription();" value="Submit" />';
		document.getElementById('descriptionbutton').innerHTML = '';
	}

	function submitDescription() {
		var txt = document.getElementById('descriptiontext').getElementsByTagName('textarea')[0].value;
		document.getElementById('descriptiontext').innerHTML = 'Updating...';
		
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
		} else {
			 req = new ActiveXObject("Microsoft.XMLHTTP");
		}
		req.open("POST", '/scripts/description.php?id=<? echo $pid; ?>', true);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
		req.send('text=' + txt);
		
		req.onreadystatechange = function() {
			if (req.readyState==4 && req.status==200) {
				document.getElementById('descriptionbutton').innerHTML = '(Edit)';
				document.getElementById('descriptiontext').innerHTML = req.responseText;
				xxtxtxx = req.responseText;
			} else {
				document.getElementById('descriptiontext').innerHTML = 'Failed (' + req.status + '). Please reload the page and try again.';
			}
		}
	}
	
	function editTitle() {
		var txt = '<?php echo js_escape(clearSymbols(file_get_contents(SRV_ROOT . '/projects/' . $pid . '/title'))); ?>'; //document.getElementById('titletext').innerHTML;
		document.getElementById('titletext').innerHTML = '<input type="text" style="width: 90%; font-size: 24px; font-weight: bold;" value="' + txt + '" onkeyup="submitTitle(event);" />';
		document.getElementById('titlebutton').innerHTML = '';
	}

	function submitTitle(e) {
		if(window.event) { // IE
			keynum = e.keyCode;
		} else if(e.which) {// Netscape/Firefox/Opera
			keynum = e.which;
		}
		if(keynum == 13) {
			var txt = document.getElementById('titletext').getElementsByTagName('input')[0].value;
			document.getElementById('titletext').innerHTML = 'Updating...';
			
			if (window.XMLHttpRequest) {
				req = new XMLHttpRequest();
			} else {
				 req = new ActiveXObject("Microsoft.XMLHTTP");
			}
			req.open("POST", '/scripts/title.php?id=<? echo $pid; ?>', true);
			req.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
			req.send('text=' + txt);
			
			req.onreadystatechange = function() {
				if (req.readyState==4 && req.status==200) {
					document.getElementById('titlebutton').innerHTML = '(Edit)';
					document.getElementById('titletext').innerHTML = req.responseText;
				} else {
					document.getElementById('titletext').innerHTML = 'Failed (' + req.status + '). Reload and try again.';
				}
			}
		} else if (keynum == 27) {
			document.getElementById('titlebutton').innerHTML = '(Edit)';
			document.getElementById('titletext').innerHTML = '<?php echo js_escape(clearSymbols(file_get_contents(SRV_ROOT . '/projects/' . $pid . '/title'))); ?>';
		}
	}
	<? } ?>
</script>
<?php } ?>
<? include SRV_ROOT . '/includes/footer.php' ?>
</div><!-- end #container -->
</body>
</html>